import { useMemo, useCallback } from 'react';

/**
 * 创建选择性状态更新的Context
 */
export const createOptimizedContext = (initialState) => {
  const Context = React.createContext();

  const Provider = ({ children }) => {
    const [state, setState] = useState(initialState);
    
    // 选择性状态更新
    const updateState = useCallback((updater) => {
      setState(prev => {
        const newState = typeof updater === 'function' 
          ? updater(prev) 
          : updater;
        
        // 浅比较决定是否更新
        return shallowEqual(prev, newState) ? prev : newState;
      });
    }, []);

    // Memo化上下文值
    const contextValue = useMemo(() => ({
      state,
      updateState
    }), [state]);

    return (
      <Context.Provider value={contextValue}>
        {children}
      </Context.Provider>
    );
  };

  function shallowEqual(objA, objB) {
    if (Object.is(objA, objB)) return true;
    
    if (typeof objA !== 'object' || objA === null ||
        typeof objB !== 'object' || objB === null) {
      return false;
    }
    
    const keysA = Object.keys(objA);
    const keysB = Object.keys(objB);
    
    if (keysA.length !== keysB.length) return false;
    
    for (let i = 0; i < keysA.length; i++) {
      if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||
          !Object.is(objA[keysA[i]], objB[keysA[i]])) {
        return false;
      }
    }
    
    return true;
  }

  const useSelector = (selector) => {
    const { state } = useContext(Context);
    return useMemo(() => selector(state), [state]);
  };

  return { Provider, useSelector };
};

/**
 * 原子状态管理器
 */
export const createAtomState = (initial) => {
  let state = initial;
  const listeners = new Set();

  const getState = () => state;

  const setState = (newState) => {
    state = typeof newState === 'function' ? newState(state) : newState;
    listeners.forEach(listener => listener());
  };

  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };

  const useAtomState = () => {
    const [localState, setLocalState] = useState(state);

    useEffect(() => {
      const unsubscribe = subscribe(() => {
        setLocalState(getState());
      });
      return unsubscribe;
    }, []);

    return [localState, setState];
  };

  return { getState, setState, subscribe, useAtomState };
};

/**
 * 状态变化订阅Hook
 */
export const useSubscription = (subscribe, getSnapshot) => {
  const [state, setState] = useState(getSnapshot);

  useEffect(() => {
    const unsubscribe = subscribe(() => {
      const newState = getSnapshot();
      setState(prev => prev === newState ? prev : newState);
    });
    return unsubscribe;
  }, [subscribe]);

  return state;
};
